/*
 * phi
 */

var tm = tm || {};

tm.WebFile = (function()
{
    var temp_class = function()
    {
        this.init.apply(this, arguments);
        return this;
    };
    
    temp_class.prototype = {
        name: null,
        type: null,
        data: null,
        
        init: function(name, type) {
            if (arguments.length > 0) { this.open.apply(this, arguments); }
            return this;
        },
        
        open: function(name, type) {
            type = type || 'r';
            this.name = name;
            this.type = type;
            
            switch ( this.type ) {
                case 'r' :
                    this.data = localStorage.getItem(name) || "";
                    break;
                case 'w' :
                    this.data = "";
                    break;
            }
            
            return this;
        },
        
        close: function() {
            switch ( this.type ) {
                case 'r' : break;
                case 'w' :
                    localStorage.setItem(this.name, this.data);
                    break;
            }
            
            this.name = "";
            this.type = "";
            this.data = null;
            
            return this;
        },
        
        write: function(str) {
            if (this.type != 'w') { alert("error: read only"); return ; }
            
            this.data += str;
            
            return this;
        },
        writeLines: function(strs) {
            if (this.type != 'w') { alert("error: read only"); return ; }
            
            for (var i=0; i<strs.length; ++i) {
                this.data += strs[i] + '\n';
            }
            
            return this;
        },
        
        read: function() {
            return this.data;
        },
        readLines: function() {
            return this.data.split('\n');
        }
    };
    
    return temp_class;
})();

tm.WebFile.test = function(){
    // write test
    (function(){
        var file = new tm.WebFile("test.txt", 'w');
        
        file.write("Test\n");
        file.writeLines(["Test0", "Test1", "Test2"]);
        
        file.close();
    })();
    
    // read test
    (function(){
        var file = new tm.WebFile("test.txt", 'r');
        
        var data = file.read();
        alert(data);
        var lines = file.readLines();
        alert(lines);
        
        file.close();
    })();
    
    // error test
    (function(){
        var file = new tm.WebFile("test.txt", 'r');
        
        file.write("test");
        file.writeLines(["test", "test", "test"])
        
        file.close();
    })();
};









